﻿@using CJAtech.BBS.DataEntity;
@{
    Layout = null;
    string categoryId = Request["categoryId"];
    //var objUserInfo = ViewBag.UserInfo as UserInfo;
    string attachUrls = "userId=" + Request["UserId"] + "&userName=" + Request["UserName"] + "&avatar" + Request["Avatar"];
}
@model CategoryInfo

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta name="format-detection" content="telephone=no,email=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="renderer" content="webkit" />
    <title>互动论坛</title>
    <link type="text/css" rel="stylesheet" href="/Content/CJCourse/pkg/base.css">
    <link type="text/css" rel="stylesheet" href="/Content/CJCourse/pkg/combine.css">
    <link type="text/css" rel="stylesheet" href="/Content/CJCourse/plugins/modal/modal.css">
    <link type="text/css" rel="stylesheet" href="/Content/CJCourse/plugins/swiper3/swiper.min.css">
    <link type="text/css" rel="stylesheet" href="/Content/CJCourse/plugins/swiper3/swiper.scale.css">
    <link type="text/css" rel="stylesheet" href="/Content/CJCourse/css/layout.css">
    <style>
        .upload-list > li .progress {
            color: #fff;
            font-size: 12px;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            height: 20px;
            line-height: 20px;
            margin: auto;
            text-align: center;
            z-index: 3;
        }
        .upload-list > li .shade{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 2;
            background-color: rgba(0,0,0,0.6);
        }
        a.remove {
            background: url(/Content/images/sprBg.png) no-repeat scroll 0 0 / 400px auto rgba(0,0,0,0);
            height: 25px;
            position: absolute;
            text-indent: -9999px;
            width: 25px;
            z-index: 5;
            top: -10px;
            right: -10px;
        }
        .upload-list > li{
            position: relative;
        }
    </style>
</head>
<body>
    <div id="wrapper">
        <div class="container nptb">
            <div class="header">
                <h5>话题发布</h5>
            </div>
            <div class="form-group">
                <div>话题标题</div>
                <div>
                    <input id="txtTitle" type="text" />
                    <div class="info text-right">限30字</div>
                </div>
            </div>
            <div class="form-group">
                <div>话题内容</div>
                <div>
                    <textarea id="txtContent"></textarea>
                    <div class="info text-right">限700字</div>
                </div>
            </div>
            <div class="form-group">
                <div>上传图片</div>
                <div>
                    <ul id="imageList" class="upload-list clearfix">
                        <li class="add-image">
                            <div id="btnUpload" style="top:0;left:0;width:100%;height:100%;position:absolute;">
                                <i id="fileList" class="icomoon icon-plus"></i>
                            </div>
                            @*<input id="fileList" type="file" multiple="multiple" class="icomoon icon-plus" style="visibility: hidden; position: absolute;">*@
                        </li>
                    </ul>
                </div>
            </div>
            <div class="margin-top-50 margin-bottom-30">
                <button id="btnSubmit" type="button" class="btn">提 交</button>
            </div>
        </div>
    </div>
    <div id="modal" class="modal-wrapper" style="display:none;">
        <div class="modal-container">
            <div class="modal-content">
                <p class="font-size-18 strong">恭喜您<br>话题发布成功</p>
                <p class="font-size-14 text-align-left">您的话题将于2个工作日内审核完毕，请耐心等待。如有问题请联系管理员，感谢您的参与！</p>
                <button id="btnConfirm" class="btn margin-top-10" style="width:50%;margin:auto;" onclick="window.location.href='/cjcourse/topiclist?categoryId=@Model.CategoryId&@attachUrls'">确定</button>
            </div>
        </div>
    </div>
    <script type="text/javascript" charset="utf-8" src="/Content/CJCourse/js/zepto/zepto.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="/Content/CJCourse/js/zepto/selector.js"></script>
    <script type="text/javascript" charset="utf-8" src="/Content/CJCourse/js/zepto/compatibleIE9.js"></script>
    <!--<script src="js/animation/tween.js"></script>-->
    <script type="text/javascript" charset="utf-8" src="/Content/CJCourse/js/fastclick/fastclick.js"></script>
    <script type="text/javascript" charset="utf-8" src="/Content/CJCourse/plugins/modal/modal.js"></script>
    <script type="text/javascript" charset="utf-8" src="/Content/CJCourse/plugins/swiper3/swiper.jquery.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="/Content/CJCourse/plugins/swiper3/swiper.scale.js"></script>
    <script type="text/javascript" charset="utf-8" src="/Content/CJCourse/js/global.js"></script>
    <script src="/Content/js/qiniu/plupload.full.min.js"></script>
    <script src="/Content/js/qiniu/qiniu.min.js"></script>
    <script type="text/javascript">

    var uploader = null;
    var locker = { lock: 0 };

    $(function () {

        initUploader();

        $("#btnSubmit").on("touchstart", function () {
            if (locker.lock > 0) return;
            locker.lock++;
            AddArticle(function () {
                setTimeout(function () { locker.lock = 0; }, 500);
            });
        });

    })


    function initUploader() {
        //上传图片
        uploader = new plupload.Uploader({
            runtimes: 'html5,flash',
            browse_button: "btnUpload",
            //file_data_name: "image",
            uptoken_url: "/QiNiuCore/GetUpLoadToken",
            url: "http://upload.qiniu.com",
            flash_swf_url: 'js/Moxie.swf',
            multi_selection: true,
            multipart_params: {},
            filters: {
                max_file_size: '10mb',
                mime_types: [{ title: "Image files", extensions: "jpg,jpeg,gif,png,bmp" }]
            },
            init: {
                PostInit: function (up) {
                    setUploadToken(up);
                },
                FilesAdded: function (up, files) {
                    if (!checkImageCount(9, files.length)) {
                        alert("图片不能超过9张");
                        return;
                    }
                    uploader.status = "uploading";
                    //禁用添加图片按钮，防止加载过程中又添加图片
                    $(".add-image input[type='file']").attr("disabled", "disabled");
                    //添加图片列表dom
                    var imageList = "";
                    for (var i = 0; i < files.length; i++) {
                        imageList += '<li id="' + files[i].id + '">' +
                                        '<div class="shade"></div>' +
                                        '<div class="progress">加载中</div>' +
                                     '</li>'
                    }
                    $("#imageList").prepend(imageList);
                    //加载dataURL
                    var delay = 300;
                    plupload.each(files, function (file, index) {
                        setTimeout(function () {
                            readAsDataURL(file.getNative(), function (url) {
                                $("#" + file.id).css("background-image", "url('" + url + "')").attr("data-url", url);
                            })
                        }, delay * index);
                    })
                    up.start();
                },
                BeforeUpload: function (up, file) {
                    setUploadToken(up);
                },
                UploadProgress: function (up, file) {
                    $("#" + file.id).find(".progress").text(file.percent + "%");
                },
                FileUploaded: function (up, file, response) {
                    var result = $.parseJSON(response.response);
                    var $li = $("#" + file.id);
                    $li.find(".progress").remove();
                    $li.find(".shade").remove();
                    $li.attr("data-key", result.key);
                    setRemoveButton($li);
                    $li.click(function (e) {
                        if (!$(e.target).hasClass("remove")) {
                            slideImage($(this).find(".image-cover"));
                        }
                    })
                },
                UploadComplete: function (up, files) {
                    uploader.status = "complete";
                    $(".add-image input[type='file']").removeAttr("disabled");
                },
                Error: function (up, error) {
                    if (error.file.size > 10000000) {
                        alert("图片不能超过10MB");
                        return;
                    }
                    alert(error.message);
                    var $li = $("#" + error.file.id);
                    $li.find(".progress").html("<span class='font-color-red'>上传失败<span>");
                    setRemoveButton($li);
                }
            }
        });
        uploader.init();
        function setRemoveButton($li) {
            $li.append('<a href="javascript:;" class="remove"></a>');
            $li.find(".remove").click(bindRemoveButton);
        }
    }

    function AddArticle(callback) {
        var error = 0;
        var title = $("#txtTitle").val();
        var content = $("#txtContent").val();
        var imageList = [];
        $("#imageList li[data-key]").each(function () {
            imageList.push($(this).attr("data-key"));
        })
        if (uploader.status == "uploading") {
            alert("图片上传未完成，请稍等...");
            error++;
        } else if (title == "") {
            alert("标题不能为空");
            $("#txtTitle").focus();
            error++;
        } else if (content == "") {
            alert("内容不能为空")
            $("#txtContent").focus();
            error++;
        } else if (title.length > 30) {
            alert("标题不能超过30字");
            error++;
        } else if (content.length > 700) {
            alert("内容不能超过700字");
            error++;
        }
        if (error == 0) {
            $.ajax({
                url: "/cjcourse/addarticle",
                type: "post",
                data: {
                    title: title,
                    content: content,
                    imageList: imageList.join(","),
                    categoryId: "@Model.CategoryId",
                    userId: "@Request["UserId"]",
                    userName: "@Request["UserName"]",
                    avatar: "@Request["Avatar"]",
                },
                success: function (data) {
                    if (data.ResultCode == "Success") {
                        clearInputContent();
                        $("#modal").modal();
                    } else {
                        alert(data.ResultMessage);
                    }
                },
                error: function (xhr, message) {
                    alert(xhr.statusText);
                },
                complete: function () {
                    callback && callback();
                }
            })
        } else {
            callback && callback();
        }
    }
    function clearInputContent() {
        $("input, textarea").val("");
        $("#imageList li[data-key]").remove();
    }
    function checkImageCount(max, addedCount) {
        var existsCount = $("#imageList li[data-key]").length;
        addedCount = addedCount ? addedCount : 0;
        var totalCount = existsCount + addedCount;
        if (totalCount > max) {
            return false
        }
        return true;
    }
    function bindRemoveButton() {
        var $this = $(this);
        var $li = $this.closest("li");
        $li.remove();
    }
    function setUploadToken(up) {
        $.ajax({
            url: "/QiNiuCore/GetUpLoadToken",
            dataType: "json",
            success: function (token) {
                if (up.settings.multipart_params) {
                    up.settings.multipart_params.token = token;
                } else {
                    up.settings.multipart_params = { token: token };
                }
            },
            error: function (message) {
                alert(message);
            }
        })
    }
    function readAsDataURL(file, onloadevent) {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            onloadevent && onloadevent(this.result)
            reader = null;
        };
    }
    </script>
</body>
</html>